﻿using Geometry.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using Geometry.Core.Services;
using Geometry.Core.Models;


namespace Geometry.Service
{
    public class TriangleService : ITriangleService
    {
        private GeometryEntities db = new GeometryEntities();

        public bool IsTriangle(int side1, int side2, int side3)
        {
            if (!(side1 >= (side2 + side3)) && !(side1 <= Math.Abs(side2 - side3)))
                return true;
            return false;
        }

        public bool IsExistSides(List<int> lst1, List<int> lst2)
        {
            lst1.Sort();
            lst2.Sort();

            for (int i = 0; i < lst1.Count; i++)
            {
                if (lst1[i] != lst2[i])
                {
                    return false;
                }
            }
            return true;
        }

        public bool Validation(Triangle model)
        {
            List<ValidationResult> errors = new List<ValidationResult>();
            if (model.Side1 == null)
            {
                errors.Add(new ValidationResult("Please enter Side1"));
            }
            if (model.Side2 == null)
            {
                errors.Add(new ValidationResult("Please enter Side2"));
            }
            if (model.Side3 == null)
            {
                errors.Add(new ValidationResult("Please enter Side3"));
            }
            if (errors.Count > 0)
            {
                return false;
            }
            return true;
        }

        public Triangle CheckExistTriangle(Triangle model)
        {
            Validation(model);
            List<int> sides = new List<int> { model.Side1.Value, model.Side2.Value, model.Side3.Value };

            //Have to use .ToList to LINQ to Entities can recognize the method
            var s = db.Triangles.ToList().FirstOrDefault(t =>
                IsExistSides(sides, (new List<int> { t.Side1.Value, t.Side2.Value, t.Side3.Value })) == true);

            return s;
        }

        public void Insert(Triangle model)
        {

            db.Triangles.Add(model);
            db.SaveChanges();

        }

        public List<TriangleResult> GetResult()
        {
            //db.p_StatisticTriangle
            return db.Database.SqlQuery<TriangleResult>("p_StatisticTriangle").ToList();
        }
    }
}
